package com.symc.sims0213xfw.controller.user;

import com.symc.sims0213xfw.bean.User;
import com.symc.sims0213xfw.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: 凤文  沈阳医学院2019级医学信息工程 0213
 * @CreateTime: 2022/01/16 10:36
 * @Description: 处理用户登录请求
 */
@WebServlet("/userLoginServlet")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uname = req.getParameter("uname");
        String upassword = req.getParameter("upassword");
        PrintWriter out = resp.getWriter();

        if (uname == null) {
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        } else if (uname.equals("") || upassword.equals("")) {
            out.write("您输入的用户名或密码为空，请重新输入<br>2秒后自动返回登录页面。。。");
            resp.setHeader("refresh", "2;url=login.jsp");
        } else {
            HttpSession session = req.getSession();
            out.write(checkUserMessage(uname, upassword, session));
            out.write("2秒后自动回到主页。。");
            resp.setHeader("refresh", "2;url=index.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    private String checkUserMessage(String uname, String upassword,
                                    HttpSession session) {
        User user = new UserServiceImpl().getUserFromDB(uname);
        if (user == null) {
            return "没有此用户！";
        } else if (!upassword.equals(user.getUpassword())) {
            return "密码输入错误！";
        }
        session.setAttribute("uname", uname);
        session.setMaxInactiveInterval(60 * 60 * 1);
        return "登录成功！";
    }
}
